package com.itboye.mengwu.buy.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.R.integer;
import android.content.Intent;
import android.graphics.LinearGradient;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.DensityUtil;
import com.itboye.core.utils.ParseDouble;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.ui.aiwujia.RedBagActivity;
import com.itboye.mengwu.app.ui.mymeng.DaiJinQuanWeiShiYong;
import com.itboye.mengwu.app.ui.mymeng.MyOrderActivity;
import com.itboye.mengwu.app.ui.mymeng.personsettings.AddressManageActivity;
import com.itboye.mengwu.data.model.AddressQueryModel;
import com.itboye.mengwu.data.model.OrderBean;
import com.itboye.mengwu.data.model.RedBagModel;
import com.itboye.mengwu.data.model.ShopCarBean;
import com.itboye.mengwu.data.model.ShopCarBeanCopy;
import com.itboye.mengwu.data.model.ShopCarBeanCopy.StoreList;
import com.itboye.mengwu.data.model.ShopCarBeanCopy.StoreList.Cart;
import com.itboye.mengwu.data.model.StoreFavourableBean;
import com.itboye.mengwu.data.presenter.AddressQueryPresenter;
import com.itboye.mengwu.data.presenter.OrderPresenter;
import com.itboye.mengwu.data.presenter.PayPresenter;
import com.itboye.mengwu.data.presenter.RedBagPresenter;
import com.itboye.mengwu.main.FragmentShopcart;

//import com.alipay.sdk.app.PayTask;

public class QueRenDingDanNew extends BaseActivity implements Observer {
	ArrayList<Cart> arrayList = new ArrayList<>();
	private ViewGroup goodsList;
	private ViewGroup other, store;
	AddressQueryPresenter addressQueryPresenter;
	TextView shouhuoInfo;
	RelativeLayout addAddress;
	private ArrayList<AddressQueryModel> array;
	private String addressId;
	ImageView back;
	TextView txt_title, ok, heji, hongbao, daijinquan, goodsTotalPrice;
	StringBuilder stringBuilder = new StringBuilder();
	String ids;
	double price;
	String type;
	private OrderPresenter orderPresenter;
	ArrayList<String> idsArray = new ArrayList<>();
	ArrayList<ShopCarBeanCopy.StoreList> arrayHash = new ArrayList<ShopCarBeanCopy.StoreList>();
	private EditText liuyan;
	StringBuffer buffer = new StringBuffer();
	boolean isLijiBuy;
	private ShopCarBean bean;
	protected String uid;
	private StoreList storeBean;
	RelativeLayout re_redbag, youhuiquan;
	private RedBagPresenter bagPresenter;
	private ArrayList<RedBagModel> arrayListRedBag;// 红包
	private ArrayList<RedBagModel> arrayListCoupon = new ArrayList<>();// 优惠券
	private String redBagId = "";
	protected String couponIds = "";
	private String getFreightCost = "";// 运费
	private TextView yunfei, youhui;
	private double youhuiHongBao, youHuiYouHuiQuan, YunFei, storeYouHui,
			goodsTotal;
	private ArrayList<EditText> arrayListEdit = new ArrayList<>();
	protected String[] noteContent=new String[]{};
	private StoreFavourableBean storeFavourableBean;
	// double yue;// 余额
	boolean hasEnableRedbag, hasEnableRevolop;
	private double prePrice;
	RelativeLayout youhuiContainer;
	private RedBagModel model;
	private double shangpinzonge;
	StringBuffer stringBufferEdit = new StringBuffer();
//	String[] notes=new String[]{};
	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_queren_dingdannew;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onMyCreate() {
		int h = DensityUtil.dip2px(5f);
		uid = SPUtils.get(QueRenDingDanNew.this, null, SpPublicParams.UID, "")
				+ "";
		orderPresenter = new OrderPresenter(this);
		txt_title.setText("确认订单");
		isLijiBuy = getIntent().getBooleanExtra("isLiJiBuy", false);
		bagPresenter = new RedBagPresenter(this);
		model = new RedBagModel();
		model.setUid((String) SPUtils.get(this, null, SpPublicParams.UID, ""));
		model.setUse_status("0");

		// getDefaultLocation();
		// type = getIntent().getStringExtra("type");
		// if (type != null) {
		// if (type.equals("2")) {
		// } else {
		// arrayList = (ArrayList<Cart>) getIntent().getSerializableExtra(
		// "list");
		//
		// }
		// }
		// idsArray=getIntent().getStringArrayListExtra("ids");
		// System.out.println("idsArray" + idsArray.size() + "");
		if (isLijiBuy == false) {
			arrayHash = (ArrayList<ShopCarBeanCopy.StoreList>) getIntent()
					.getSerializableExtra("list");
			for (int i = 1; i < arrayList.size(); i++) {
				stringBuilder.append(arrayList.get(i).getId() + ",");
			}
			if (stringBuilder.length() > 0) {
				ids = stringBuilder.substring(0, stringBuilder.length() - 1);
			}

			for (int i = 0; i < arrayHash.size(); i++) {
				int singleCount = 0;
				double singlePrice = 0;
				View viewStore = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.querendingdan_goodsandstore, null);
				TextView storeName = (TextView) viewStore
						.findViewById(R.id.storeName);
				TextView single_count = (TextView) viewStore
						.findViewById(R.id.single_count);
				TextView single_heji = (TextView) viewStore
						.findViewById(R.id.single_heji);
				LinearLayout top = (LinearLayout) viewStore
						.findViewById(R.id.top);
				TextView dianPuyouhui = (TextView) viewStore
						.findViewById(R.id.dianPuyouhui);
				liuyan = (EditText) viewStore.findViewById(R.id.liuyan);
				arrayListEdit.add(liuyan);
				if (arrayHash.get(i).getCondition() != null
						&& arrayHash.get(i).getDiscountMoney() != null)
					dianPuyouhui.setText("满" + arrayHash.get(i).getCondition()
							+ "减" + arrayHash.get(i).getDiscountMoney());
				else
					dianPuyouhui.setText("店铺暂时没有提供优惠哦,敬请期待");
				storeName.setText(arrayHash.get(i).getName());
				store.addView(viewStore);
				// orderPresenter.getStoreFavourable(storeBean.getId());
				int tempPosition = 0;
				for (int j = 0; j < arrayHash.get(i).getCarts().size(); j++) {
					if (arrayHash.get(i).getCarts().get(j).isSelected()) {
						tempPosition = j;
						// price += (Double.parseDouble(arrayHash.get(i)
						// .getCarts().get(j).getPrice()) * Integer
						// .parseInt(arrayHash.get(i).getCarts().get(j)
						// .getCount()));
						singleCount += Integer.parseInt(arrayHash.get(i)
								.getCarts().get(j).getCount());
						singlePrice += Double.parseDouble(arrayHash.get(i)
								.getCarts().get(j).getPrice())
								* Integer.parseInt(arrayHash.get(i).getCarts()
										.get(j).getCount());
						buffer.append(arrayHash.get(i).getCarts().get(j)
								.getId()
								+ "-");
						View v = LayoutInflater.from(getApplicationContext())
								.inflate(R.layout.querendingdan_header3, null);
						ImageView img = (ImageView) v.findViewById(R.id.img);
						TextView name = (TextView) v.findViewById(R.id.name);
						TextView guige = (TextView) v.findViewById(R.id.guige);
						TextView jiage = (TextView) v.findViewById(R.id.jiage);
						TextView shuliang = (TextView) v
								.findViewById(R.id.shuliang);
						name.setText(arrayHash.get(i).getCarts().get(j)
								.getName());
						guige.setText(arrayHash.get(i).getCarts().get(j)
								.getSkuDesc());
						jiage.setText("￥"
								+ arrayHash.get(i).getCarts().get(j).getPrice());
						shuliang.setText("x"
								+ arrayHash.get(i).getCarts().get(j).getCount());
						XImageLoader.load(GlobalConfig.API_URL
								+ "/picture/index?id="
								+ arrayHash.get(i).getCarts().get(j)
										.getIconUrl(), img);
						android.widget.LinearLayout.LayoutParams layoutParams = new android.widget.LinearLayout.LayoutParams(
								android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
								android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
						layoutParams.setMargins(5, 5, 5, 5);
						top.addView(v, layoutParams);
						View divider = new View(getApplicationContext());
						divider.setLayoutParams(new LayoutParams(
								LayoutParams.MATCH_PARENT, h));
						divider.setBackgroundColor(getResources().getColor(
								R.color.white));
						// goodsList.addView(divider);

					}
					if (j == arrayHash.get(i).getCarts().size() - 1) {
						buffer = buffer.delete(buffer.length() - 1,
								buffer.length());
						buffer.append(",");
					}
					// goodsList.addView(divider);
				}
				shangpinzonge += singlePrice;
				// View viewYouHui =
				// LayoutInflater.from(getApplicationContext())
				// .inflate(R.layout.querendingdan_header1, null);
				// // yunfei = (TextView) viewYouHui
				// // .findViewById(R.id.yunfei);
				// // if (arrayHash.get(i).getFreeShipping().equals("0")) {
				// // yunfei.setText("包邮");fdsf
				// // } else {
				// // yunfei.setText("不包邮");
				// // }
				// TextView dianPuyouhui = (TextView) viewYouHui
				// .findViewById(R.id.dianPuyouhui);
				// dianPuyouhui.setText("满" + arrayHash.get(i).getCondition()
				// + "减" + arrayHash.get(i).getDiscountMoney());
				// // storeYouHui = Double.parseDouble(arrayHash.get(i)
				// // .getDiscountMoney());
				// liuyan = (EditText) viewYouHui.findViewById(R.id.liuyan);
				// arrayListEdit.add(liuyan);
				// other.addView(viewYouHui);
				// buffer.append(arrayHash.get(i).getCarts().get(j)
				// .getId()
				// + "-");
				single_count.setText("共" + singleCount + "件商品");
				if (arrayHash.get(i).getCondition() != null
						&& arrayHash.get(i).getDiscountMoney() != null) {
					if (singlePrice < Double.parseDouble(arrayHash.get(i)
							.getCondition()))
						single_heji.setText(Html.fromHtml("合计 共："
								+ "<font color='#FF6EA5'>￥" + singlePrice
								+ "</font>"));
					else {
						singlePrice = singlePrice
								- Double.parseDouble(arrayHash.get(i)
										.getDiscountMoney());
						single_heji.setText(Html.fromHtml("合计 共："
								+ "<font color='#FF6EA5'>￥" + singlePrice
								+ "</font>"));
					}
				} else {
					single_heji.setText(Html.fromHtml("合计 共："
							+ "<font color='#FF6EA5'>￥" + singlePrice
							+ "</font>"));
				}
				price += singlePrice;
			}
			System.out.println("拼接后的字符串：" + buffer);
			goodsTotalPrice.setText(Html.fromHtml("合计 共："
					+ "<font color='#FF6EA5'>￥" + shangpinzonge + "</font>"));
			getDefaultLocation();
			// orderPresenter.getStoreFavourable(storeBean.getId());
		} else {
			storeBean = (StoreList) getIntent().getSerializableExtra("model");
			View v = LayoutInflater.from(getApplicationContext()).inflate(
					R.layout.querendingdan_header3, null);
			ImageView img = (ImageView) v.findViewById(R.id.img);
			TextView name = (TextView) v.findViewById(R.id.name);
			TextView guige = (TextView) v.findViewById(R.id.guige);
			TextView jiage = (TextView) v.findViewById(R.id.jiage);
			TextView shuliang = (TextView) v.findViewById(R.id.shuliang);
//			liuyan = (EditText) v.findViewById(R.id.liuyan);
			name.setText(storeBean.getCarts().get(0).getName());
			guige.setText(storeBean.getCarts().get(0).getSkuDesc());
			jiage.setText("￥" + storeBean.getCarts().get(0).getPrice());
			price = Double.parseDouble(storeBean.getCarts().get(0).getCount())
					* Double.parseDouble(storeBean.getCarts().get(0).getPrice());
			goodsTotalPrice.setText("￥" + price);
			orderPresenter.getStoreFavourable(storeBean.getId());
			shuliang.setText("x" + storeBean.getCarts().get(0).getCount());
			XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
					+ storeBean.getCarts().get(0).getIconUrl(), img);
			android.widget.LinearLayout.LayoutParams layoutParams = new android.widget.LinearLayout.LayoutParams(
					android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
					android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
			layoutParams.setMargins(5, 5, 5, 5);
			goodsList.addView(v, layoutParams);
			orderPresenter.getStoreFavourable(storeBean.getId());
			getDefaultLocation();
			// View divider = new View(getApplicationContext());
			// divider.setLayoutParams(new LayoutParams(
			// LayoutParams.MATCH_PARENT, h));
			// divider.setBackgroundColor(getResources().getColor(
			// R.color.white));
			// goodsList.addView(divider);
		}

		// heji.setText(ParseDouble.getDouble(price) + "");
		addAddress.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(QueRenDingDanNew.this,
						AddressManageActivity.class);
				intent.putExtra("type", 1);
				startActivityForResult(intent, 101);
			}
		});
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		// 跳转红包
		re_redbag.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (hasEnableRedbag) {
					Intent intent = new Intent(QueRenDingDanNew.this,
							RedBagActivity.class);
					intent.putExtra("price", prePrice);
					startActivityForResult(intent, 103);
				}
			}
		});

		youhuiquan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (hasEnableRevolop) {
					Intent intent = new Intent(QueRenDingDanNew.this,
							DaiJinQuanWeiShiYong.class);
					intent.putExtra("price", prePrice);
					startActivityForResult(intent, 104);
				} else {

				}
			}
		});

		/**
		 * 提交订单
		 */
		ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				noteContent = new String[arrayListEdit.size()];
				for (int i = 0; i < arrayListEdit.size(); i++) {
					noteContent[i] = arrayListEdit.get(i).getText().toString();
				}
				if (isLijiBuy) {
					System.out.println(storeBean.getCarts().get(0).getPId()
							+ ":" + storeBean.getCarts().get(0).getCount()
							+ ":" + storeBean.getCarts().get(0).getPskuId()
							+ ":" + price + ":" + addressId);
					Log.e("money", price + "");
					// if (toggle_button.isChecked()) {
					// orderPresenter.buyInstant(uid, storeBean.getCarts()
					// .get(0).getPId(), storeBean.getCarts().get(0)
					// .getCount(), storeBean.getCarts().get(0)
					// .getPskuId(), redBagId, couponIds, price + "",
					// noteContent, addressId, "android");
					// } else {
					orderPresenter.buyInstant(uid, storeBean.getCarts().get(0)
							.getPId(), storeBean.getCarts().get(0).getCount(),
							storeBean.getCarts().get(0).getPskuId(), redBagId,
							couponIds, "", "", addressId, "android","");
					// }

				} else {
					// if (toggle_button.isChecked()) {
					// OrderBean model = new OrderBean();
					// model.setUid(uid);
					// model.setCartIds(buffer.toString().substring(0,
					// buffer.toString().length() - 2));
					// model.setAddressId(addressId);
					// model.setRedIds(redBagId);// 红包
					// model.setCouponIds(couponIds);
					// model.setMoney(price + "");
					// model.setNotes(noteContent);
					// orderPresenter.add(model);
					// } else {
					OrderBean model = new OrderBean();
					model.setUid(uid);
					model.setCartIds(buffer.toString().substring(0,
							buffer.toString().length() - 1));
					model.setAddressId(addressId);
					model.setRedIds(redBagId);// 红包
					model.setCouponIds(couponIds);
					model.setNotes(noteContent);
					orderPresenter.add(model);
					// }
				}
			}
		});
	}

	private void caculateTotalPrice() {
		System.out.println("各种抵扣" + price + ":" + YunFei + ":" + youhuiHongBao
				+ ":" + youHuiYouHuiQuan + ":" + storeYouHui);
		prePrice = price + YunFei;
		price = price + YunFei - youhuiHongBao - youHuiYouHuiQuan;
		if (price <= 0) {
			price = 0.01;
		}
		heji.setText("￥" + price);
		heji.setTag(price);
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == 101 && arg1 == 102) {
			if (arg2 != null) {
				addressId = arg2.getStringExtra("id");
				shouhuoInfo.setText(arg2.getStringExtra("wholelocation")
						+ arg2.getStringExtra("detail") + "\n"
						+ arg2.getStringExtra("name") + "     "
						+ arg2.getStringExtra("phone"));
			}
		} else if (arg0 == 103 && arg1 == 105) {// 红包回调
			String redMoney = arg2.getStringExtra("redMoney");
			youhuiHongBao = Double.parseDouble(redMoney);
			redBagId = arg2.getStringExtra("redId");
			hongbao.setText("红包-￥" + redMoney);
			caculateTotalPrice();
		} else if (arg0 == 104 && arg1 == 106) {// 优惠券回调
			String youHuiMoney = arg2.getStringExtra("youHuiMoney");
			youHuiYouHuiQuan = Double.parseDouble(youHuiMoney);
			redBagId = arg2.getStringExtra("youHuiId");
			daijinquan.setText("优惠券-￥" + youHuiMoney);
			caculateTotalPrice();
		}
	}

	private void getDefaultLocation() {
		// TODO Auto-generated method stub
		addressQueryPresenter = new AddressQueryPresenter(this);
		addressQueryPresenter.queryAddress((String) SPUtils.get(this, null,
				SpPublicParams.UID, ""));
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == AddressQueryPresenter.AddressQuerySuccessEvent) {
				array = (ArrayList<AddressQueryModel>) entity.getData();
				for (int i = 0; i < array.size(); i++) {
					if (array.get(i).getDefault() == 1) {
						shouhuoInfo.setText(array.get(i).getProvince()
								+ array.get(i).getCity()
								+ array.get(i).getArea()
								+ array.get(i).getDetailinfo() + "\n"
								+ array.get(i).getContactname() + "     "
								+ array.get(i).getMobile());
						addressId = array.get(i).getId();
					} else {
						shouhuoInfo.setText(array.get(0).getProvince()
								+ array.get(0).getCity()
								+ array.get(0).getArea()
								+ array.get(0).getDetailinfo() + "\n"
								+ array.get(0).getContactname() + "     "
								+ array.get(0).getMobile());
						addressId = array.get(0).getId();
					}
				}
				if (!isLijiBuy) {
					Log.v("suoyou ", buffer.toString());
					bagPresenter.caculateFreightCost(
							uid,
							addressId,
							buffer.toString().substring(0,
									buffer.toString().length() - 1));
				} else {
					bagPresenter.caculateFreightCost(uid, addressId, storeBean
							.getCarts().get(0).getPId(), storeBean.getCarts()
							.get(0).getCount());
				}
				bagPresenter.query(model);// 获取优惠券
			} else if (entity.getEventType() == OrderPresenter.OrderShengchengSuccess) {
//				ByAlert.alert("成功");
				Intent intentBroad = new Intent(FragmentShopcart.changeCart);// 通知购物车界面更新UI
				sendBroadcast(intentBroad);
				OrderBean bean = (OrderBean) entity.getData();
				Intent intent = new Intent(QueRenDingDanNew.this,
						PayTypeActivity.class);
				intent.putExtra("model", bean);
				startActivity(intent);
				finish();
			} else if (entity.getEventType() == OrderPresenter.OrderShengchengFail) {
				ByAlert.alert("失败");
			} else if (entity.getEventType() == OrderPresenter.PayInstant_success) {

				Intent intentBroad = new Intent(FragmentShopcart.changeCart);// 通知购物车界面更新UI
				sendBroadcast(intentBroad);

				//ByAlert.alert(entity.getData() + "");
				OrderBean bean = (OrderBean) entity.getData();
				Intent intent = new Intent(QueRenDingDanNew.this,
						PayTypeActivity.class);
				intent.putExtra("model", bean);
				startActivity(intent);
				finish();
			} else if (entity.getEventType() == OrderPresenter.PayInstant_Fail) {
				ByAlert.alert("失败" + entity.getData() + "");
			} else if (entity.getEventType() == RedBagPresenter.QueryRedBagSuccess) {
				arrayListRedBag = (ArrayList<RedBagModel>) entity.getData();
				RedBagModel aa = new RedBagModel();
				// 红包通过money排序
				for (int i = 0; i < arrayListRedBag.size(); i++) {

					for (int j = i + 1; j < arrayListRedBag.size(); j++) {
						if (Double.parseDouble(arrayListRedBag.get(i)
								.getMoney().trim()) < Double
								.parseDouble(arrayListRedBag.get(j).getMoney()
										.trim())) {
							aa = arrayListRedBag.get(i);
							arrayListRedBag.set(i, arrayListRedBag.get(j));
							arrayListRedBag.set(j, aa);

						}
					}
				}

				for (int i = 0; i < arrayListRedBag.size(); i++) {// 删除不满足优惠条件的红包
					if (Double.parseDouble(arrayListRedBag.get(i)
							.getUse_condition()) > price) {
						arrayListRedBag.remove(i);
					}
				}
				Iterator<RedBagModel> iterable = arrayListRedBag.iterator();
				while (iterable.hasNext()) {// 删除优惠金额大于应付金额的红包
					RedBagModel type = iterable.next();
					if (Double.parseDouble(type.getMoney()) > price) {
						iterable.remove();
					}
				}

				// setValue(arrayListRedBag, 1);
				// for (RedBagModel string : arrayListRedBag) {
				// System.out.println("moby" + string.getMoney());
				// }
				if (arrayListRedBag.size() > 0) {
					hongbao.setText("红包-￥" + arrayListRedBag.get(0).getMoney());
					youhuiHongBao = Double.parseDouble(arrayListRedBag.get(0)
							.getMoney());

					hasEnableRedbag = true;
					redBagId = arrayListRedBag.get(0).getId();
				} else {
					hasEnableRedbag = false;
					hongbao.setText("没有达到条件的红包");
				}
				// hongbao.setText(arrayListRedBag.get(0).getName());
			} else if (entity.getEventType() == RedBagPresenter.QueryRedBagFail) {

			} else if (entity.getEventType() == RedBagPresenter.QueryCouponSuccess) {
				arrayListCoupon = (ArrayList<RedBagModel>) entity.getData();
				RedBagModel aa = new RedBagModel();
				// 优惠券通过money排序
				for (int i = 0; i < arrayListCoupon.size(); i++) {

					for (int j = i + 1; j < arrayListCoupon.size(); j++) {
						Log.e("1111", i + "");
						Log.e("2222", j + "");
						if (Double.parseDouble(arrayListCoupon.get(i)
								.getMoney().trim()) < Double
								.parseDouble(arrayListCoupon.get(j).getMoney()
										.trim())) {
							aa = arrayListCoupon.get(i);
							arrayListCoupon.set(i, arrayListCoupon.get(j));
							arrayListCoupon.set(j, aa);

						}
					}
				}

				for (int i = 0; i < arrayListCoupon.size(); i++) {// 删除不满足优惠条件的红包
					System.out.println("优惠券"
							+ arrayListCoupon.get(i).getUse_condition() + "L:"
							+ price);
					if (Double.parseDouble(arrayListCoupon.get(i)
							.getUse_condition()) > price) {
						arrayListCoupon.remove(i);
					}
				}
				System.out.println("前size" + arrayListCoupon.size());
				// for (int i = 0; i < arrayListRedBag.size(); i++) {
				// System.out.println("金额："+arrayListRedBag.get(i).getMoney()+":"+price);
				// if(Double.parseDouble(arrayListRedBag.get(i).getMoney())>price){
				// //
				// System.out.println("要移除的"+arrayListRedBag.get(i).getMoney()+":"+price);
				// arrayListRedBag.remove(i);
				// }
				// }
				Iterator<RedBagModel> iterable = arrayListCoupon.iterator();
				while (iterable.hasNext()) {// 删除优惠金额大于应付金额的红包
					RedBagModel type = iterable.next();
					if (Double.parseDouble(type.getMoney()) > price) {
						iterable.remove();
					}
				}

				for (RedBagModel iterable_element : arrayListCoupon) {
					System.out.println("红包" + iterable_element.getId() + ":"
							+ iterable_element.getMoney());
				}
				if (arrayListCoupon.size() > 0) {
					hasEnableRevolop = true;

					daijinquan.setText("优惠券-￥"
							+ arrayListCoupon.get(0).getMoney());
					youHuiYouHuiQuan = Double.parseDouble(arrayListCoupon
							.get(0).getMoney());
					couponIds = arrayListCoupon.get(0).getId();
				} else {
					hasEnableRevolop = false;
					daijinquan.setText("没有达到条件的优惠券");
				}
				bagPresenter.getInfo(model);// 获取红包
			} else if (entity.getEventType() == RedBagPresenter.QueryCouponFail) {

			} else if (entity.getEventType() == RedBagPresenter.QueryFreightCostSuccess) {
//				ByAlert.alert(entity.getData() + "");
				yunfei.setText(entity.getData().equals("0") ? "包邮" : "￥"
						+ entity.getData());
				YunFei = Double.parseDouble(entity.getData() + "");
				caculateTotalPrice();
			} else if (entity.getEventType() == RedBagPresenter.QueryFreightCostFail) {
				ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == RedBagPresenter.QueryFreightCostGoodsSuccess) {
				// ByAlert.alert(entity.getData() + "");
				yunfei.setText(entity.getData().equals("0") ? "包邮" : "￥"
						+ entity.getData());
				YunFei = Double.parseDouble(entity.getData() + "");
				caculateTotalPrice();
			} else if (entity.getEventType() == RedBagPresenter.QueryFreightCostGoodsFail) {
				ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == OrderPresenter.getFavourableSuccess) {
				storeFavourableBean = (StoreFavourableBean) entity.getData();
				if (price > Double.parseDouble(storeFavourableBean
						.getDicountMoney())) {
					storeYouHui = Double.parseDouble(storeFavourableBean
							.getCondition());
					youhui.setText("-￥" + storeFavourableBean.getDicountMoney());
					caculateTotalPrice();
				} else {
					youhui.setText("不满足优惠条件");
				}
			}

		}
	}

	/**
	 * 冒泡排序
	 * 
	 * @param list
	 *            需要排序的集合
	 * @param type
	 *            排序类型 0：正序 1：倒序
	 * */
	public void setValue(ArrayList<RedBagModel> list, int type) {
		System.out.println("价格" + price);
		for (int i = 0; i < list.size(); i++) {
			if (Double.parseDouble(list.get(i).getUse_condition()) > price) {
				list.remove(i);
			}
		}
		for (int i = 0; i < list.size(); i++) {// 循环List集合，开始于下标0

			for (int j = i + 1; j < list.size(); j++) {// 循环List集合，开始于下标0+1
				double a = Double.parseDouble(list.get(i).getMoney());// 取List集合的第n个值
				double b = Double.parseDouble(list.get(j).getMoney());// 取List集合的第n+1个值
				if (type == 0 ? a > b : a < b) {// 如果a比b大，则替换两个值的位置。
					list.set(i, list.get(j));
					list.set(j, list.get(i));
				}
			}
		}

	}
}
